package doc2db.interfaces.action;

import doc2db.DbManager.DbSelects;
import doc2db.Keey;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileWorker;
import doc2db.table.DocTable;
import doc2db.table.DocTableCell;
import doc2db.table.DocTableHead;
import java.awt.HeadlessException;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author yura
 */
public class Doc2DbCheckTab {

    private String tabName;

    public Doc2DbCheckTab(String tabName) {
        this.tabName = tabName;
    }

    boolean checTabInDb(DocTable tab, int i) {
        String tname = "tabel_name_doc2db_" + tabName + i;
        if (Keey.tableName && Keey.tableNameValue.trim().length() > 1) {
            tname = Keey.tableNameValue.trim();
        }
        if (!this.isTableExsist(tname)) {
            return true;
        }

        String[][] str = getTableMetaData(tname);
        String[] strName = new String[str.length];

        for (int j = 0; j < strName.length; j++) {
            strName[j] = "" + str[j][3];
        }

        String[] strType = new String[str.length];

        for (int j = 0; j < strType.length; j++) {
            strType[j] = "" + str[j][4];
        }
        
        boolean b = mkDialog(tname, tab, strName, strType);

        return b;
    }

    private boolean mkDialog(String tname, DocTable tab, String[] strName, String[] strType)
            throws HeadlessException {
        String sqlTable = "Создатётся таблица с полями :\n" + tab.getHead().getSQLString();
        boolean columnName = this.isColumnName(tab.getHead(), strName);
        boolean columnType = this.isColumnType(tab.getHead(), strName, strType);

        if (Keey.isIsMas()){
            if ( (! columnName) & (! columnType) ){
                return true;
            }
        }


        Object[] btns = {"Продолжить", "Прекратить", "Разрешить конфликт"};

        String html = getHtml(tname, sqlTable, columnName, columnType);

        String msgtitl = "doc2db проверка таблицы";

        int res = JOptionPane.showOptionDialog(null, html, msgtitl,
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE,
                null, btns, btns[2]);

        if (res == JOptionPane.YES_OPTION){
            String str = columnName & columnType ? " - данные могут не внестись" : "";
            System.out.println("Продолжить для '" + tname + "' " + str);
        }

        if (res == JOptionPane.NO_OPTION){
            String str = columnName & columnType ? "? - Oшибки не было б" : "";
            System.out.println("Прекратить '" + tname + "' " + str);
        }

        if (res == JOptionPane.CANCEL_OPTION){
            System.out.println("Разрешить");
            ConflictOutbreak co = new ConflictOutbreak(tname);
            boolean b = co.coordinatTableStruct(tab.getHead(), strName);
            if (b){
                res = JOptionPane.YES_OPTION;
            } else {
                JOptionPane.showMessageDialog(null, co.getMsg(), msgtitl, 0);
                System.err.println(co.getMsg());
            }
        }

        boolean b = res == JOptionPane.YES_OPTION;

        return b;
    }

    private String getHtml(String tabName, String masage, boolean isColumName, boolean isColumType) {
        StringBuilder sb = new StringBuilder()
                .append("<html><body><font styrle=monospaced  name=monospaced size=4>")
                .append("<P>таблица с именем \'").append(tabName)
                .append(", уже существует:<br><ol><li>");
        if (isColumName) {
            sb.append(" название полей <b color=red>НЕ</b> совпадают");
        } else {
            sb.append(" название полей совпадают");
        }
        sb.append("</li><li>");
        if (isColumType) {
            sb.append(" типы данных полей <b color=red>НЕ</b> совпадают");
        } else {
            sb.append(" типы данных полей совпадают");
        }
        sb.append("</li></ol></P><P><pre>").append(masage);

        return sb.toString();
    }

    private boolean isTableExsist(String n) {
        UserProp up = new UserProp();
        try {
            DbSelects query = new DbSelects(up.getURL(), up.getUserProp());
            return query.sendQuery("SELECT * from \"" + n + "\"  LIMIT 1;");
        } catch (SQLException ex) {
            return false;
        } catch (ClassNotFoundException ex) {
            return false;
        }

    }

    private boolean isColumnName(DocTableHead h, String[] dbSelect) {
        for (String nh : h.get()) {
            boolean b = true;
            for (String dbn : dbSelect) {
                if (dbn == null ? nh == null : dbn.equals(nh)){
                    b = false;
                    break;
                }
            }
            if (b){
                return true;
            }
        }
        return false;
    }

    private boolean isColumnType(DocTableHead h, String[] names, String[] types) {
        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            String type = types[i];
            boolean b = false;
            for (int j = 0; j < h.getSize(); j++) {
                DocTableCell get = h.get(j);
                String hname = get.getName();
                String htype = get.getHead();
                if (name == null ? hname == null : name.equals(hname)){
                    b = (type == null ? htype == null : type.equals(htype));
                    break;
                }
            }
            if (b){
                return true;
            }
        }
        return false;
    }

    private String[][] getTableMetaData(String tableName) {
        String[][] result = null;
        UserProp up = new UserProp();
        String str = getTabDataSql(tableName);
        try {
            DbSelects query = new DbSelects(up.getURL(), up.getUserProp());
            if (query.sendQuery(str)) {
                int rows = query.getRows();
                int cols = query.getColumns();
                result = new String[rows][cols];
                for (int i = 1; i <= rows; i++) {
                    for (int j = 1; j <= cols; j++) {
                        result[i - 1][j - 1] = "" + query.getString(i, j);
                    }
                }
            }
        } catch (Exception ex) {
        }

        return result;
    }

    private String getTabDataSql(String tableName) {
        String path = FileBeginer.resurse_resurseFolder + Keey.sp + FileBeginer.sqlSelects;
        String str = FileWorker.howInit(path, "tableProp")
                .replaceAll("DB_NAME", "" + UserProp.dbName)
                .replaceAll("\'TABLE_NAME\'", "\'" + tableName + "\'");
        return str;
    }
}
